import dotProp from 'dot-prop';
import got from 'got';
import chalk from 'chalk';
import {dirname, basename, join} from 'path';

type saveLayoutProps = {
  track: {[key: string]: any};
  path: string;
  minimumIntegerDigits: number;
  trackNumber: boolean;
};

export const saveLayout = ({track, path, minimumIntegerDigits, trackNumber}: saveLayoutProps) => {
  const file = path.match(/(?<=\{)[^\}]*/g);
  if (file) {
    for (const key of file) {
      const value: string | undefined = dotProp.get(track, key);
      path = path.replace('{' + key + '}', value ? value : '');
    }
  }

  if (trackNumber && (track.TRACK_NUMBER || track.TRACK_POSITION)) {
    const [dir, base] = [dirname(path), basename(path)];
    const position = track.TRACK_POSITION ? track.TRACK_POSITION : Number(track.TRACK_NUMBER);
    path = join(dir, position.toLocaleString('en-US', {minimumIntegerDigits, useGrouping: false}) + ' - ' + base);
  }

  return path.replace(/[?%*:|"<>]/g, '').trim();
};

export const getFileSize = async (downloadUrl: string, fileSize: number) => {
  try {
    if (fileSize > 0) {
      return fileSize;
    }

    const {headers} = await got.head(downloadUrl);
    return Number(headers['content-length']);
  } catch (err) {
    return 0;
  }
};

export const progressBar = (total: number, width: number) => {
  const incomplete = Array(width).fill('█').join('');
  const complete = Array(width).fill('█').join('');
  const unit = total / width;

  return (value: number) => {
    let chars = unit === 0 ? width : Math.floor(value / unit);
    if (value >= total) {
      chars = complete.length;
    }
    return chalk.cyanBright(complete.slice(0, chars)) + chalk.gray(incomplete.slice(chars));
  };
};
